package com.example.show_auto

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.runtime.*
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.foundation.verticalScroll
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.show_auto.data.Guest
import com.example.show_auto.data.Recipe
import com.example.show_auto.data.SettingsStorage
import com.example.show_auto.data.UpdateManager
import com.example.show_auto.data.UpdateInfo
import android.content.Intent
import android.net.Uri
import kotlin.system.exitProcess
import com.example.show_auto.ui.components.DrawerMenu
import com.example.show_auto.ui.pages.GuestQueryPage
import com.example.show_auto.ui.pages.PersonalDataPage
import com.example.show_auto.ui.pages.RecipeCalculatorPage
import com.example.show_auto.ui.pages.GuestRateCalculatorPage
import com.example.show_auto.ui.pages.SystemConfigPage
import com.example.show_auto.ui.pages.UsageGuidePage
import com.example.show_auto.ui.pages.ComprehensiveQueryNewPage
import com.example.show_auto.ui.pages.TableProfitResultPage
import com.example.show_auto.ui.pages.ChefCategoryQueryPage
import com.example.show_auto.ui.theme.ShowautoTheme
import com.example.show_auto.ui.utils.DeviceCompatibility
import com.example.show_auto.ui.utils.OppoCompatibilityFix
import com.example.show_auto.utils.NetworkUtils
import com.example.show_auto.viewmodel.MainViewModel
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            val settingsStorage = remember { SettingsStorage(this@MainActivity) }
            var themeMode by remember { mutableStateOf(settingsStorage.getThemeMode()) }
            val isSystemInDarkTheme = isSystemInDarkTheme()
            
            // 监听主题变化
            LaunchedEffect(Unit) {
                while (true) {
                    kotlinx.coroutines.delay(1000) // 每秒检查一次主题设置
                    val currentThemeMode = settingsStorage.getThemeMode()
                    if (currentThemeMode != themeMode) {
                        themeMode = currentThemeMode
                    }
                }
            }
            
            val isDarkTheme = when (themeMode) {
                1 -> false // 强制浅色
                2 -> true  // 强制深色
                else -> isSystemInDarkTheme // 跟随系统
            }
            
            ShowautoTheme(darkTheme = isDarkTheme) {
                MainApp()
            }
        }
    }
}

/**
 * 主应用组件 - 带侧边菜单的导航应用
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainApp() {
    // 应用全局兼容性修复
    OppoCompatibilityFix.applyGlobalFixes()

    val viewModel: MainViewModel = viewModel()
    val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
    val scope = rememberCoroutineScope()

    var currentPage by remember { mutableStateOf("home") }
    var currentSubPage by remember { mutableStateOf<String?>(null) }

    // 自动更新相关状态
    var autoUpdateInfo by remember { mutableStateOf<UpdateInfo?>(null) }
    var showAutoUpdateDialog by remember { mutableStateOf(false) }
    
    // 网络连接检查状态
    var isNetworkAvailable by remember { mutableStateOf(true) }
    var showNetworkDialog by remember { mutableStateOf(false) }
    var isCheckingNetwork by remember { mutableStateOf(false) }

    // 应用启动时优先检查网络连接
    val context = androidx.compose.ui.platform.LocalContext.current
    LaunchedEffect(Unit) {
        scope.launch {
            try {
                isCheckingNetwork = true
                val hasNetwork = NetworkUtils.isNetworkAvailable(context)
                isNetworkAvailable = hasNetwork
                
                if (!hasNetwork) {
                    showNetworkDialog = true
                    return@launch // 没有网络时，停止后续的所有初始化操作
                }
            } catch (e: Exception) {
                // 网络检查失败，视为无网络
                isNetworkAvailable = false
                showNetworkDialog = true
                return@launch
            } finally {
                isCheckingNetwork = false
            }
        }
    }

    // 应用启动时自动同步游戏数据（仅在有网络时执行）
    LaunchedEffect(isNetworkAvailable) {
        if (!isNetworkAvailable) return@LaunchedEffect
        scope.launch {
            try {
                val gameDataManager = com.example.show_auto.data.GameDataManager(context)
                val result = gameDataManager.syncGameDataFromNetwork()
                if (result.isSuccess) {
                    // 同步成功后，通知ViewModel重新加载数据
                    viewModel.reloadGameData()
                }
            } catch (e: Exception) {
                // 静默处理同步失败，不影响应用启动
            }
        }
    }

    // 应用启动时检查强制更新状态和自动检查更新（仅在有网络时执行）
    LaunchedEffect(isNetworkAvailable) {
        if (!isNetworkAvailable) return@LaunchedEffect
        scope.launch {
            try {
                val updateManager = UpdateManager(context)
                val settingsStorage = SettingsStorage(context)
                
                // 首先检查是否有待处理的强制更新
                if (settingsStorage.hasForceUpdatePending()) {
                    // 如果有强制更新待处理，立即检查更新
                    val updateInfo = updateManager.checkForUpdate()
                    if (updateInfo.hasUpdate && updateInfo.forceUpdate) {
                        autoUpdateInfo = updateInfo
                        showAutoUpdateDialog = true
                        return@launch // 直接返回，不执行后续的自动检查
                    } else {
                        // 如果检查后发现不再需要强制更新，清除状态
                        settingsStorage.clearForceUpdatePending()
                    }
                }
                
                // 正常的自动检查更新
                val updateInfo = updateManager.autoCheckForUpdate()
                if (updateInfo != null && updateInfo.hasUpdate) {
                    autoUpdateInfo = updateInfo
                    showAutoUpdateDialog = true
                }
            } catch (e: Exception) {
                // 静默处理检查更新失败
            }
        }
    }

    // 检查是否处于强制更新状态，如果是则阻止用户使用应用
    val isForceUpdateBlocked = remember { mutableStateOf(false) }
    
    LaunchedEffect(showAutoUpdateDialog, autoUpdateInfo) {
        // 如果显示强制更新对话框，阻止用户使用应用
        isForceUpdateBlocked.value = showAutoUpdateDialog && autoUpdateInfo?.forceUpdate == true
    }
    
    if (!isNetworkAvailable || showNetworkDialog) {
        // 没有网络连接时，阻止用户使用应用
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                if (isCheckingNetwork) {
                    CircularProgressIndicator()
                    Text(
                        text = "正在检查网络连接...",
                        style = MaterialTheme.typography.bodyLarge,
                        color = MaterialTheme.colorScheme.onSurface
                    )
                } else {
                    Icon(
                        imageVector = Icons.Default.Warning,
                        contentDescription = null,
                        tint = MaterialTheme.colorScheme.error,
                        modifier = Modifier.size(48.dp)
                    )
                    Text(
                        text = "网络连接不可用",
                        style = MaterialTheme.typography.headlineMedium,
                        color = MaterialTheme.colorScheme.error,
                        fontWeight = FontWeight.Bold
                    )
                    Text(
                        text = "此应用需要网络连接才能正常使用\n请检查您的网络设置",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurface,
                        textAlign = TextAlign.Center
                    )
                }
            }
        }
    } else if (isForceUpdateBlocked.value) {
        // 强制更新时，只显示更新对话框，不显示应用内容
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = "正在检查更新...",
                style = MaterialTheme.typography.bodyLarge,
                color = MaterialTheme.colorScheme.onSurface
            )
        }
    } else {
        ModalNavigationDrawer(
            drawerState = drawerState,
            drawerContent = {
                DrawerMenu(
                    currentPage = currentPage,
                    onMenuItemClick = { pageId ->
                        currentPage = pageId
                        currentSubPage = null // 重置子页面
                        scope.launch {
                            drawerState.close()
                        }
                    }
                )
            }
        ) {
        // 根据当前页面显示不同内容
        when (currentPage) {
            "home" -> HomePage(
                viewModel = viewModel,
                onMenuClick = {
                    scope.launch {
                        drawerState.open()
                    }
                }
            )
            "personal_data" -> PersonalDataPage(
                viewModel = viewModel,
                onMenuClick = {
                    scope.launch {
                        drawerState.open()
                    }
                }
            )
            "guest_query" -> GuestQueryPage(
                viewModel = viewModel,
                onMenuClick = {
                    scope.launch {
                        drawerState.open()
                    }
                }
            )
            "rune_query" -> GuestRateCalculatorPage(
                viewModel = viewModel,
                onMenuClick = {
                    scope.launch {
                        drawerState.open()
                    }
                }
            )
            "recipe_calculator" -> RecipeCalculatorPage(
                viewModel = viewModel,
                onMenuClick = {
                    scope.launch {
                        drawerState.open()
                    }
                }
            )
            "usage_guide" -> UsageGuidePage(
                onMenuClick = {
                    scope.launch {
                        drawerState.open()
                    }
                }
            )
            "system_config" -> SystemConfigPage(
                onMenuClick = {
                    scope.launch {
                        drawerState.open()
                    }
                }
            )
            "comprehensive_query" -> com.example.show_auto.ui.pages.ComprehensiveQueryPage(
                onMenuClick = {
                    scope.launch {
                        drawerState.open()
                    }
                }
            )
            "comprehensive_query_new" -> {
                when (currentSubPage) {
                    "table_profit" -> TableProfitResultPage(
                        onMenuClick = {
                            scope.launch {
                                drawerState.open()
                            }
                        },
                        onBackClick = {
                            currentSubPage = null
                        }
                    )
                    "chef_category" -> ChefCategoryQueryPage(
                        onMenuClick = {
                            scope.launch {
                                drawerState.open()
                            }
                        },
                        onBackClick = {
                            currentSubPage = null
                        }
                    )
                    else -> ComprehensiveQueryNewPage(
                        onMenuClick = {
                            scope.launch {
                                drawerState.open()
                            }
                        },
                        onNavigateToTableProfit = {
                            currentSubPage = "table_profit"
                        },
                        onNavigateToChefCategory = {
                            currentSubPage = "chef_category"
                        }
                    )
                }
            }
        }
    }
    }

    // 自动更新对话框
    if (showAutoUpdateDialog && autoUpdateInfo != null) {
        val updateInfo = autoUpdateInfo!!
        AlertDialog(
            onDismissRequest = { 
                if (!updateInfo.forceUpdate) {
                    showAutoUpdateDialog = false 
                } else {
                    // 强制更新时，拒绝更新则退出应用
                    exitProcess(0)
                }
            },
            title = { 
                Text(
                    text = if (updateInfo.forceUpdate) "强制更新" else "发现新版本",
                    color = if (updateInfo.forceUpdate) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary
                ) 
            },
            text = {
                Column(
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    Text("最新版本：v${updateInfo.latestVersion}")
                    Text("当前版本：v${updateInfo.currentVersion}")
                    
                    if (updateInfo.updateMessage.isNotEmpty()) {
                        HorizontalDivider()
                        Text(
                            text = "更新内容：",
                            fontWeight = FontWeight.Bold,
                            color = MaterialTheme.colorScheme.primary
                        )
                        SelectionContainer {
                            Text(
                                text = updateInfo.updateMessage,
                                style = MaterialTheme.typography.bodyMedium
                            )
                        }
                    }
                    
                    if (updateInfo.forceUpdate) {
                        HorizontalDivider()
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            Icon(
                                Icons.Default.Warning,
                                contentDescription = null,
                                tint = MaterialTheme.colorScheme.error
                            )
                            Text(
                                text = "此版本为强制更新，必须更新后才能继续使用应用\n点击任何位置拒绝更新将自动退出应用",
                                color = MaterialTheme.colorScheme.error,
                                fontWeight = FontWeight.Bold
                            )
                        }
                    }
                }
            },
            confirmButton = {
                Button(
                    onClick = {
                        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(updateInfo.downloadUrl))
                        context.startActivity(intent)
                        if (!updateInfo.forceUpdate) {
                            showAutoUpdateDialog = false
                        } else {
                            // 强制更新时，跳转到下载页面后退出应用
                            // 保持强制更新状态，确保用户必须完成更新才能重新进入应用
                            exitProcess(0)
                        }
                    }
                ) {
                    Text(if (updateInfo.forceUpdate) "立即更新" else "立即更新")
                }
            },
            dismissButton = if (!updateInfo.forceUpdate) {
                {
                    TextButton(
                        onClick = { showAutoUpdateDialog = false }
                    ) {
                        Text("稍后更新")
                    }
                }
            } else null
        )
    }

    // 网络连接对话框
    if (showNetworkDialog) {
        AlertDialog(
            onDismissRequest = { 
                // 不允许关闭对话框，必须有网络才能使用应用
            },
            title = {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Warning,
                        contentDescription = null,
                        tint = MaterialTheme.colorScheme.error
                    )
                    Text(
                        text = "需要网络连接",
                        color = MaterialTheme.colorScheme.error
                    )
                }
            },
            text = {
                Column(
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    Text(
                        text = "此应用需要网络连接才能正常使用。",
                        style = MaterialTheme.typography.bodyMedium
                    )
                    Text(
                        text = "请确保您的设备已连接到互联网，然后点击\"重新检查\"。",
                        style = MaterialTheme.typography.bodyMedium
                    )
                    HorizontalDivider()
                    Text(
                        text = "注意：应用需要网络连接来确保数据安全和版本更新。",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        fontStyle = androidx.compose.ui.text.font.FontStyle.Italic
                    )
                }
            },
            confirmButton = {
                Button(
                    onClick = {
                        scope.launch {
                            isCheckingNetwork = true
                            try {
                                val hasNetwork = NetworkUtils.isNetworkAvailable(context)
                                isNetworkAvailable = hasNetwork
                                if (hasNetwork) {
                                    showNetworkDialog = false
                                }
                            } catch (e: Exception) {
                                isNetworkAvailable = false
                            } finally {
                                isCheckingNetwork = false
                            }
                        }
                    },
                    enabled = !isCheckingNetwork
                ) {
                    if (isCheckingNetwork) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(16.dp),
                            strokeWidth = 2.dp
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                    }
                    Text(if (isCheckingNetwork) "检查中..." else "重新检查")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = {
                        // 退出应用
                        exitProcess(0)
                    }
                ) {
                    Text("退出应用")
                }
            }
        )
    }
}

/**
 * 首页组件 - 只显示应用名称
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomePage(
    viewModel: MainViewModel,
    onMenuClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier.fillMaxSize()
    ) {
        // 顶部应用栏
        TopAppBar(
            title = {
                Text(
                    text = "",
                    fontWeight = FontWeight.Medium
                )
            },
            navigationIcon = {
                IconButton(onClick = onMenuClick) {
                    Icon(
                        imageVector = Icons.Default.Menu,
                        contentDescription = "菜单"
                    )
                }
            },
            colors = TopAppBarDefaults.topAppBarColors(
                containerColor = MaterialTheme.colorScheme.primaryContainer,
                titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
                navigationIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer
            )
        )

        // 主页内容 - 只显示轮椅标题
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = "请坐",
                fontSize = 48.sp,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.primary
            )
        }
    }
}



@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainScreen(
    modifier: Modifier = Modifier,
    viewModel: MainViewModel = viewModel()
) {
    val uiState by viewModel.uiState.collectAsState()
    val guests by viewModel.guests.collectAsState()
    val filteredRecipes by viewModel.filteredRecipes.collectAsState()

    var codeInput by remember { mutableStateOf(TextFieldValue("")) }
    var expanded by remember { mutableStateOf(false) }

    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        // 标题
        Text(
            text = "查询助手",
            fontSize = 24.sp,
            fontWeight = FontWeight.Bold,
            textAlign = TextAlign.Center,
            modifier = Modifier.fillMaxWidth()
        )

        // 错误信息显示
        uiState.error?.let { error ->
            Card(
                colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer),
                modifier = Modifier.fillMaxWidth()
            ) {
                Text(
                    text = error,
                    color = MaterialTheme.colorScheme.onErrorContainer,
                    modifier = Modifier.padding(16.dp)
                )
            }
        }

        // 校验码输入区域
        if (!uiState.isCodeValid) {
            Card(
                modifier = Modifier.fillMaxWidth()
            ) {
                Column(
                    modifier = Modifier.padding(16.dp),
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    Text(
                        text = "请输入官方校验码",
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Medium
                    )

                    OutlinedTextField(
                        value = codeInput,
                        onValueChange = { codeInput = it },
                        label = { Text("校验码") },
                        placeholder = { Text("输入官方提供的校验码") },
                        modifier = Modifier
                            .fillMaxWidth()
                            .pointerInput(Unit) {
                                detectTapGestures(
                                    onLongPress = {
                                        // 长按全选
                                        if (codeInput.text.isNotEmpty()) {
                                            codeInput = codeInput.copy(
                                                selection = TextRange(0, codeInput.text.length)
                                            )
                                        }
                                    },
                                    onDoubleTap = {
                                        // 双击全选
                                        if (codeInput.text.isNotEmpty()) {
                                            codeInput = codeInput.copy(
                                                selection = TextRange(0, codeInput.text.length)
                                            )
                                        }
                                    }
                                )
                            },
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
                        enabled = !uiState.isValidating,
                        singleLine = true
                    )

                    Button(
                        onClick = {
                            viewModel.validateCode(codeInput.text)
                        },
                        modifier = Modifier.fillMaxWidth(),
                        enabled = !uiState.isValidating
                    ) {
                        if (uiState.isValidating) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(16.dp),
                                color = MaterialTheme.colorScheme.onPrimary
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                        }
                        Text(if (uiState.isValidating) "验证中..." else "验证并生成个人数据")
                    }

                    // 测试提示
                    Text(
                        text = "测试模式：可输入 'test' 或 'debug' 进行测试",
                        fontSize = 12.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
        }

        // 数据加载状态
        if (uiState.isLoading) {
            Box(
                modifier = Modifier.fillMaxWidth(),
                contentAlignment = Alignment.Center
            ) {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    CircularProgressIndicator()
                    Text("正在加载游戏数据...")
                }
            }
        }

        // 主要功能区域（校验成功后显示）
        if (uiState.isCodeValid && uiState.isDataLoaded) {
            // 成功提示
            Card(
                colors = CardDefaults.cardColors(containerColor = Color(0xFF4CAF50).copy(alpha = 0.1f)),
                modifier = Modifier.fillMaxWidth()
            ) {
                Text(
                    text = "✓ 校验成功！个人数据已生成",
                    color = Color(0xFF4CAF50),
                    fontWeight = FontWeight.Medium,
                    modifier = Modifier.padding(16.dp)
                )
            }

            // 贵客选择区域
            Card(
                modifier = Modifier.fillMaxWidth()
            ) {
                Column(
                    modifier = Modifier.padding(16.dp),
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    Text(
                        text = "选择贵客",
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Medium
                    )

                    ExposedDropdownMenuBox(
                        expanded = expanded,
                        onExpandedChange = { expanded = !expanded }
                    ) {
                        OutlinedTextField(
                            value = uiState.selectedGuest?.let { it.name } ?: "",
                            onValueChange = {},
                            readOnly = true,
                            label = { Text("选择贵客") },
                            placeholder = { Text("请选择要查询的贵客") },
                            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
                            modifier = Modifier
                                .menuAnchor()
                                .fillMaxWidth()
                        )

                        ExposedDropdownMenu(
                            expanded = expanded,
                            onDismissRequest = { expanded = false }
                        ) {
                            guests.forEach { guest ->
                                DropdownMenuItem(
                                    text = {
                                        Text(guest.name)
                                    },
                                    onClick = {
                                        viewModel.selectGuest(guest)
                                        expanded = false
                                    }
                                )
                            }
                        }
                    }
                }
            }

            // 菜谱列表
            if (filteredRecipes.isNotEmpty()) {
                Card(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp)
                    ) {
                        Text(
                            text = "符合条件的菜谱 (${filteredRecipes.size}个)",
                            fontSize = 18.sp,
                            fontWeight = FontWeight.Medium,
                            modifier = Modifier.padding(bottom = 12.dp)
                        )

                        LazyColumn(
                            verticalArrangement = Arrangement.spacedBy(8.dp),
                            modifier = Modifier.heightIn(max = 400.dp)
                        ) {
                            items(filteredRecipes) { recipe ->
                                RecipeItem(recipe = recipe)
                            }
                        }
                    }
                }
            } else if (uiState.selectedGuest != null) {
                Card(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Text(
                        text = "未找到符合条件的菜谱",
                        textAlign = TextAlign.Center,
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(32.dp)
                    )
                }
            }
        }
    }
}

@Composable
fun RecipeItem(
    recipe: Recipe,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = when (recipe.rarity) {
                1 -> Color(0xFFE8F5E8)
                2 -> Color(0xFFE3F2FD)
                3 -> Color(0xFFFFF3E0)
                4 -> Color(0xFFFCE4EC)
                5 -> Color(0xFFF3E5F5)
                else -> MaterialTheme.colorScheme.surface
            }
        )
    ) {
        Column(
            modifier = Modifier.padding(12.dp),
            verticalArrangement = Arrangement.spacedBy(4.dp)
        ) {
            // 菜谱名称和星级
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = recipe.name,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Medium
                )
                Text(
                    text = recipe.getRarityStars(),
                    fontSize = 14.sp,
                    color = Color(0xFFFF9800)
                )
            }

            // 技法要求
            if (recipe.getSkillRequirements().isNotEmpty()) {
                Text(
                    text = "技法: ${recipe.getSkillRequirements()}",
                    fontSize = 12.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }

            // 当前品阶
            Text(
                text = "当前品阶: ${getRankText(recipe.rank)}",
                fontSize = 12.sp,
                color = MaterialTheme.colorScheme.primary
            )

            // 升阶贵客
            val rankGuests = recipe.getRankGuests()
            if (rankGuests.isNotEmpty()) {
                Text(
                    text = "升阶贵客: ${rankGuests.joinToString(", ")}",
                    fontSize = 12.sp,
                    color = MaterialTheme.colorScheme.secondary
                )
            }

            // 来源
            if (recipe.origin.isNotEmpty()) {
                Text(
                    text = "来源: ${recipe.origin}",
                    fontSize = 11.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    }
}

/**
 * 获取品阶文本
 */
private fun getRankText(rank: Int): String {
    return when (rank) {
        0 -> "未制作"
        1 -> "普通"
        2 -> "优级"
        3 -> "特级"
        4 -> "神级"
        else -> "未知"
    }
}

@Preview(showBackground = true)
@Composable
fun MainScreenPreview() {
    ShowautoTheme {
        MainScreen()
    }
}

@Preview(showBackground = true)
@Composable
fun RecipeItemPreview() {
    ShowautoTheme {
        RecipeItem(
            recipe = Recipe(
                name = "白切鸡",
                rarity = 2,
                knife = 5,
                boil = 3,
                origin = "粤菜",
                got = true,
                rank = 3,
                guests = listOf(
                    com.example.show_auto.data.RecipeGuest("白玉汤", 1),
                    com.example.show_auto.data.RecipeGuest("孟婆", 2)
                )
            )
        )
    }
}